package com.ppmall.util;

import com.ppmall.task.ScheduleTask;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

public class ScheduleUtil {


    private static ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    private static Map<String, ScheduledFuture<?>> scheduledFutureMap = new HashMap<>();

    static {
        threadPoolTaskScheduler.initialize();
        System.out.println("time pool start");
    }

    public static void start(ScheduleTask scheduleTask, Date starttime){
        ScheduledFuture<?> scheduledFuture = threadPoolTaskScheduler.schedule(scheduleTask, starttime);
        scheduledFutureMap.put(scheduleTask.getId(), scheduledFuture);
        System.out.println("time task start" + scheduleTask.getId() + DateUtil2.parseDateToStr(starttime, DateUtil2.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));

    }

    public static void cancel(ScheduleTask scheduleTask){
        ScheduledFuture<?> scheduledFuture = scheduledFutureMap.get(scheduleTask.getId());
        if(scheduledFuture != null && !scheduledFuture.isCancelled()){
            scheduledFuture.cancel(false);
        }
        scheduledFutureMap.remove(scheduleTask.getId());
        System.out.println("取消定时任务" + scheduleTask.getId());
    }


    public static void reset(ScheduleTask scheduleTask, Date starttime){
        ScheduledFuture<?> scheduledFuture = scheduledFutureMap.get(scheduleTask.getId());
        if(scheduledFuture != null && !scheduledFuture.isCancelled()){
            scheduledFuture.cancel(false);
        }
        scheduledFutureMap.remove(scheduleTask.getId());
        scheduledFuture = threadPoolTaskScheduler.schedule(scheduleTask, starttime);
        scheduledFutureMap.put(scheduleTask.getId(), scheduledFuture);
        System.out.println("修改定时任务" + scheduleTask.getId() + "为" + DateUtil2.parseDateToStr(starttime, DateUtil2.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
    }

}
